<template>
  <view class="content">
    <!-- 单个用户登录 -->
    <view class="user-group">
      <button @click="loginUser">登录用户</button>
    </view>

    <!-- 消息发送部分（移除发送者选择） -->
    <view class="send-group">
      <input v-model="targetUserId" placeholder="目标用户ID" class="target-input" />
      <input v-model="message" placeholder="输入消息" class="message-input" />
      <button @click="sendMessage" :disabled="!currentUser.socket || currentUser.reconnecting">
        发送
      </button>
    </view>

    <!-- 统一消息展示 -->
    <view class="messages">
      <view v-for="(msg, index) in messages" :key="index" class="message-item">
        {{ msg }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onUnmounted, onMounted } from 'vue'
import { http } from '../../utils/requestUtil'
import { login } from '../../utils/tokenUtil'
// import uni from '@dcloudio/uni-app'

// 单个用户状态（移除多用户数组）
const currentUser = reactive({
  username: 'test1', // 固定用户名（可改为从配置获取）
  password: '12345',
  token: '',
  userId: '101',
  socket: null,
  reconnecting: false,
  reconnectTimer: null,
  reconnectInterval: 1000 // 初始重连间隔1秒
})

const targetUserId = ref('')
const message = ref('')
const messages = ref([])
const reconnectCount=ref(0)
// 登录逻辑（简化为单个用户）
const loginUser = async () => {
  try {
    // 清除旧连接和重连定时器
    clearReconnectTimer(currentUser)
    
    const res = await login(currentUser.username, currentUser.password)
    currentUser.token = uni.getStorageSync('token') || '' // 修复原代码直接使用硬编码的问题
    
    initWebSocket(currentUser)
    uni.showToast({ title: '登录成功', icon: 'success' })
  } catch (error) {
    uni.showToast({ title: '登录失败', icon: 'error' })
  }
}

const initWebSocket = (user) => {
  const socketTask = uni.connectSocket({
    url: `ws://localhost:8080/ws/endpoint/${user.token}`,
    success: () => {
      console.log('连接创建成功')
    }
  })

  socketTask.onOpen(() => {
    messages.value.push(`系统：连接成功`)
    user.reconnectInterval = 1000 // 重置重连间隔
  })

  socketTask.onMessage((res) => {
    try {
      const data = JSON.parse(res.data)
      messages.value.push(`收到 ${data.fromUserId} 的消息：${data.content}`)
    } catch {
      messages.value.push(`收到原始消息：${res.data}`)
    }
  })

  socketTask.onError((err) => {
    messages.value.push(`系统：连接出错，准备重连...`)
    startReconnect(user, socketTask)
  })

  socketTask.onClose((res) => {
    if (res.code !== 1000) { // 非正常关闭时重连
      messages.value.push(`系统：连接断开（状态码${res.code}），准备重连...`)
	  reconnectCount.value=reconnectCount++;
	  if(reconnectCount.value>=5){
		  messages.value.push(`最大重连`)
	  }
      startReconnect(user, socketTask)
    } else {
      messages.value.push(`系统：连接已正常关闭`)
    }
  })

  user.socket = socketTask
}

// 重连逻辑（简化为单个用户）
const startReconnect = (user, oldSocket) => {
  if (user.reconnecting || !user.token) return // 防止重复重连
  
  oldSocket?.close()
  user.socket = null
  user.reconnecting = true
  
  const maxInterval = 30000 // 最大重连间隔30秒
  user.reconnectInterval = Math.min(user.reconnectInterval * 2, maxInterval)
  
  user.reconnectTimer = setTimeout(() => {
    messages.value.push(`系统：尝试重连（间隔${user.reconnectInterval/1000}秒）`)
    initWebSocket(user)
    user.reconnecting = false
  }, user.reconnectInterval)
}

const clearReconnectTimer = (user) => {
  clearTimeout(user.reconnectTimer)
  user.reconnectTimer = null
  user.reconnecting = false
}

// 发送消息（移除多用户判断）
const sendMessage = () => {
  if (!message.value.trim() || !targetUserId.value) {
    messages.value.push(`系统：请填写目标用户ID和消息内容`)
    return
  }

  const user = currentUser
  if (!user.socket || user.reconnecting) {
    messages.value.push(`系统：连接中，请稍后再试`)
    return
  }

  const msgData = JSON.stringify({
    fromUserId: user.userId,
    toUserId: targetUserId.value,
    content: message.value.trim()
  })

  user.socket.send({
    data: msgData,
    success: () => {
      messages.value.push(`发送给 ${targetUserId.value}：${message.value.trim()}`)
      message.value = ''
    },
    fail: (err) => {
      messages.value.push(`系统：发送失败（${err.errMsg}），即将重连...`)
      startReconnect(user, user.socket)
    }
  })
}


import { eventBus } from '../../utils/eventBus';

const handleEvent = (data) => console.log('收到数据:', data);

onMounted(() => eventBus.on('custom-event', handleEvent));
// 组件卸载处理
onUnmounted(() => {
  clearReconnectTimer(currentUser)
  currentUser.socket?.close()
})
</script>

<style>
/* 简化后的样式（移除发送者选择相关样式） */
.content {
  padding: 20px;
}

.user-group button {
  margin: 5px;
  padding: 8px;
}

.send-group {
  margin: 15px 0;
  display: flex;
  gap: 5px;
}

.target-input, .message-input {
  flex: 1;
  border: 1px solid #ccc;
  padding: 8px;
}

.messages {
  margin-top: 20px;
  border-top: 1px solid #eee;
}

.message-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
}
</style>